import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { topCategory } from "@/apis/const";

interface CategoryState {
  list: any[];
}
const useCategoryStore = createSlice({
  name: "any",
  initialState: {
    list: [] as any[],
  } as CategoryState,
  reducers: {
    setList: {
      reducer(state, action: PayloadAction<any[]>) {
        state.list = action.payload;
      },
      prepare(payload: any[]) {
        const temp = payload.map((item) => ({
          ...item,
          open: false,
        }));
        return { payload: temp };
      },
    },
    setConst(state) {
      state.list = topCategory.map((item) => ({ name: item }));
    },
    setShow(state, action: PayloadAction<number>) {
      const id = action.payload;
      state.list = state.list.map((item) =>
        item.id === id ? { ...item, open: true } : item
      );
    },
    setHide(state, action: PayloadAction<number>) {
      const id = action.payload;
      state.list = state.list.map((item) =>
        item.id === id ? { ...item, open: false } : item
      );
    },
  },
});

export const { setList, setConst, setShow, setHide } = useCategoryStore.actions;
const categoryReducer = useCategoryStore.reducer;
export default categoryReducer;
